package com.sam.java;

public class SynchronizedTest {
    public synchronized void syncMethod(){//同步方法,不能是抽象方法或者接口方法
        //代码
        print("syncMethod");
    }

    private static void print(String string) {
        for (int i = 0; i < 10; i++) {
            System.out.println(string + ", " + i);
        }
    }

    public void syncThis(){
        synchronized (this){//同步块
            //代码
            print("同步块");
        }
    }

    public void syncClassMethod(){
        synchronized (SynchronizedTest.class){//同步class对象
            //代码
            print("同步class对象");
        }
    }

    public synchronized static void syncStaticMethod(){//同步静态方法
        //代码
        print("同步静态方法");
    }


    public static void main(String[] args) {
        SynchronizedTest synchronizedTest = new SynchronizedTest();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                synchronizedTest.syncClassMethod();
            }
        };
        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                synchronizedTest.syncStaticMethod();
            }
        };

        new Thread(runnable).start();
        new Thread(runnable2).start();
    }


}
